package OptimalAlgorithm.Linkedlist;
//https://leetcode.cn/problems/swap-nodes-in-pairs/description/
public class SwapPairs {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode newHead = new ListNode(0,head);
        ListNode prev = newHead;
        ListNode cur = head;
        ListNode next = head.next;
        ListNode nnext = head.next.next;
        while (cur != null && next != null){
            //交换节点
            prev.next = next;
            next.next = cur;
            cur.next = nnext;
            //移动指向
            prev = cur;
            cur = nnext;
            if(cur != null){
                next = cur.next;
            }
            if(next != null){
                nnext = next.next;
            }
        }
        return newHead.next;
    }
}
